/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConfigBibliotecaWindow.java
 *
 * Created on 23-may-2011, 0:03:43
 */
package GUI;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Pik
 */
public class ConfigBibliotecaWindow extends javax.swing.JFrame {

    private String[] lista;
    private String ruta;

    /** Creates new form ConfigBibliotecaWindow */
    public ConfigBibliotecaWindow() {
        initComponents();

    }

    /**
     * Inicializa la lista de directorios.
     * @param rutaArchivoConfig Ruta del archivo txt que contiene la lista de directorios.
     */
    public void inicializar(String rutaArchivoConfig) {
        this.ruta = rutaArchivoConfig;
        try {
            File f = new File(rutaArchivoConfig);
            if (!f.exists()) {
                this.lista = null;
            } else {
                BufferedReader in = new BufferedReader(new FileReader(f));
                String linea = in.readLine();
                int contador = 0;
                while (linea != null) {
                    contador++;
                    linea = in.readLine();
                }
                in.close();
                this.lista = new String[contador];
                in = null;
                in = new BufferedReader(new FileReader(rutaArchivoConfig));
                linea = in.readLine();
                contador = 0;
                while (linea != null) {
                    this.lista[contador] = linea;
                    contador++;
                    linea = in.readLine();
                }
                this.listaDirectorios.setListData(lista);
            }
        } catch (IOException e) {
            this.lista = null;
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listaDirectorios = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        botonAñadir = new javax.swing.JButton();
        botonQuitar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(560, 362));

        jScrollPane1.setViewportView(listaDirectorios);

        jTextPane1.setContentType("text/html");
        jTextPane1.setText("<html>\r\n<head>\r\n\n</head>\r\n<body>\r\n\t<p style=\"margin-top: 0\">\r\n\t<center><b>Lista de directorios incluídos en la biblioteca</b> \n<p> Cuando se pulsa en <i>Opciones/Refrescar</i> o F5, estos directorios se revisan en busca de nuevas canciones. </p>\n<p>Para añadir directorios a la lista, pulse el botón <i>Añadir</i> y escoja los directorios deseados.</p>\n<p>Para eliminar un directorio de la lista, selecciónelo y pulse el botón <i>Quitar</i>. </p> \n  </body>\r\n</html>\r\n");
        jScrollPane2.setViewportView(jTextPane1);

        botonAñadir.setLabel("Añadir");
        botonAñadir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAñadirActionPerformed(evt);
            }
        });

        botonQuitar.setLabel("Quitar");
        botonQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonQuitarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(botonAñadir, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 240, Short.MAX_VALUE)
                .addComponent(botonQuitar, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE))
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(301, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonQuitar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botonAñadir, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(64, 64, 64)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonAñadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAñadirActionPerformed
        JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
        fc.setDialogTitle("Añadir directorio");
        fc.setDialogType(JFileChooser.OPEN_DIALOG);
        fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter());
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setMultiSelectionEnabled(true);
        int result = fc.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File[] rutas = fc.getSelectedFiles();
            int c;
            String[] listaAux;
            if (this.lista != null) {
                listaAux = this.lista;
                c = listaAux.length;
                this.lista = new String[c + rutas.length];
                for (int i = 0; i < listaAux.length; i++) {
                    lista[i] = listaAux[i];
                }
            } else {
                c = 0;
                this.lista = new String[rutas.length];
            }
            for (int i = 0; i < rutas.length; i++) {
                this.lista[i + c] = rutas[i].getAbsolutePath();
            }
            try {
                File f = new File(this.ruta);
                if (f.exists()) {
                    f.delete();
                }
                f.createNewFile();
                BufferedWriter w = new BufferedWriter(new FileWriter(f));
                for (int i = 0; i < this.lista.length; i++) {
                    w.write(this.lista[i]);
                    w.newLine();
                }
                w.close();

            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "Ocurrió un error al grabar el archivo de configuración.", "Problema", JOptionPane.ERROR_MESSAGE);
            }
            this.listaDirectorios.setListData(lista);
        }
    }//GEN-LAST:event_botonAñadirActionPerformed

    private void botonQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonQuitarActionPerformed
        int[] seleccion = this.listaDirectorios.getSelectedIndices();
        for (int i = 0; i < seleccion.length; i++) {
            this.lista[seleccion[i]] = null;
        }
        String[] listaAux;
        listaAux = this.lista;
        this.lista = new String[listaAux.length - seleccion.length];
        int contador = 0;
        for (int i = 0; i < listaAux.length; i++) {
            if (listaAux[i] != null) {
                this.lista[contador] = listaAux[i];
                contador++;
            }
        }
        try {
            File f = new File(this.ruta);
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();
            BufferedWriter w = new BufferedWriter(new FileWriter(f));
            for (int i = 0; i < this.lista.length; i++) {
                w.write(this.lista[i]);
                w.newLine();
            }
            w.close();

        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "Ocurrió un error al grabar el archivo de configuración.", "Problema", JOptionPane.ERROR_MESSAGE);
        }
        this.listaDirectorios.setListData(lista);
    }//GEN-LAST:event_botonQuitarActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAñadir;
    private javax.swing.JButton botonQuitar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JList listaDirectorios;
    // End of variables declaration//GEN-END:variables
}
